{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# DiffEdit"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Image editing typically requires providing a mask of the area to be edited. DiffEdit automatically generates the mask for you based on a text query, making it easier overall to create a mask without image editing software. The DiffEdit algorithm works in three steps:\n",
    "\n",
    "1. the diffusion model denoises an image conditioned on some query text and reference text which produces different noise estimates for different areas of the image; the difference is used to infer a mask to identify which area of the image needs to be changed to match the query text\n",
    "2. the input image is encoded into latent space with DDIM\n",
    "3. the latents are decoded with the diffusion model conditioned on the text query, using the mask as a guide such that pixels outside the mask remain the same as in the input image\n",
    "\n",
    "This guide will show you how to use DiffEdit to edit images without manually creating a mask.\n",
    "\n",
    "Before you begin, make sure you have the following libraries installed:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# uncomment to install the necessary libraries in Colab\n",
    "#!pip install -q diffusers transformers accelerate"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The [StableDiffusionDiffEditPipeline](https://huggingface.co/docs/diffusers/main/en/api/pipelines/diffedit#diffusers.StableDiffusionDiffEditPipeline) requires an image mask and a set of partially inverted latents. The image mask is generated from the [generate_mask()](https://huggingface.co/docs/diffusers/main/en/api/pipelines/diffedit#diffusers.StableDiffusionDiffEditPipeline.generate_mask) function, and includes two parameters, `source_prompt` and `target_prompt`. These parameters determine what to edit in the image. For example, if you want to change a bowl of *fruits* to a bowl of *pears*, then:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "source_prompt = \"a bowl of fruits\"\n",
    "target_prompt = \"a bowl of pears\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The partially inverted latents are generated from the [invert()](https://huggingface.co/docs/diffusers/main/en/api/pipelines/diffedit#diffusers.StableDiffusionDiffEditPipeline.invert) function, and it is generally a good idea to include a `prompt` or *caption* describing the image to help guide the inverse latent sampling process. The caption can often be your `source_prompt`, but feel free to experiment with other text descriptions!\n",
    "\n",
    "Let's load the pipeline, scheduler, inverse scheduler, and enable some optimizations to reduce memory usage:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "from diffusers import DDIMScheduler, DDIMInverseScheduler, StableDiffusionDiffEditPipeline\n",
    "\n",
    "pipeline = StableDiffusionDiffEditPipeline.from_pretrained(\n",
    "    \"stabilityai/stable-diffusion-2-1\",\n",
    "    torch_dtype=torch.float16,\n",
    "    safety_checker=None,\n",
    "    use_safetensors=True,\n",
    ")\n",
    "pipeline.scheduler = DDIMScheduler.from_config(pipeline.scheduler.config)\n",
    "pipeline.inverse_scheduler = DDIMInverseScheduler.from_config(pipeline.scheduler.config)\n",
    "pipeline.enable_model_cpu_offload()\n",
    "pipeline.enable_vae_slicing()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Load the image to edit:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from diffusers.utils import load_image, make_image_grid\n",
    "\n",
    "img_url = \"https://github.com/Xiang-cd/DiffEdit-stable-diffusion/raw/main/assets/origin.png\"\n",
    "raw_image = load_image(img_url).resize((768, 768))\n",
    "raw_image"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Use the [generate_mask()](https://huggingface.co/docs/diffusers/main/en/api/pipelines/diffedit#diffusers.StableDiffusionDiffEditPipeline.generate_mask) function to generate the image mask. You'll need to pass it the `source_prompt` and `target_prompt` to specify what to edit in the image:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from PIL import Image\n",
    "\n",
    "source_prompt = \"a bowl of fruits\"\n",
    "target_prompt = \"a basket of pears\"\n",
    "mask_image = pipeline.generate_mask(\n",
    "    image=raw_image,\n",
    "    source_prompt=source_prompt,\n",
    "    target_prompt=target_prompt,\n",
    ")\n",
    "Image.fromarray((mask_image.squeeze()*255).astype(\"uint8\"), \"L\").resize((768, 768))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Next, create the inverted latents and pass it a caption describing the image:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "inv_latents = pipeline.invert(prompt=source_prompt, image=raw_image).latents"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Finally, pass the image mask and inverted latents to the pipeline. The `target_prompt` becomes the `prompt` now, and the `source_prompt` is used as the `negative_prompt`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "output_image = pipeline(\n",
    "    prompt=target_prompt,\n",
    "    mask_image=mask_image,\n",
    "    image_latents=inv_latents,\n",
    "    negative_prompt=source_prompt,\n",
    ").images[0]\n",
    "mask_image = Image.fromarray((mask_image.squeeze()*255).astype(\"uint8\"), \"L\").resize((768, 768))\n",
    "make_image_grid([raw_image, mask_image, output_image], rows=1, cols=3)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<div class=\"flex gap-4\">\n",
    "  <div>\n",
    "    <img class=\"rounded-xl\" src=\"https://github.com/Xiang-cd/DiffEdit-stable-diffusion/raw/main/assets/origin.png\"/>\n",
    "    <figcaption class=\"mt-2 text-center text-sm text-gray-500\">original image</figcaption>\n",
    "  </div>\n",
    "  <div>\n",
    "    <img class=\"rounded-xl\" src=\"https://github.com/Xiang-cd/DiffEdit-stable-diffusion/blob/main/assets/target.png?raw=true\"/>\n",
    "    <figcaption class=\"mt-2 text-center text-sm text-gray-500\">edited image</figcaption>\n",
    "  </div>\n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Generate source and target embeddings"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The source and target embeddings can be automatically generated with the [Flan-T5](https://huggingface.co/docs/transformers/model_doc/flan-t5) model instead of creating them manually.\n",
    "\n",
    "Load the Flan-T5 model and tokenizer from the 🤗 Transformers library:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "from transformers import AutoTokenizer, T5ForConditionalGeneration\n",
    "\n",
    "tokenizer = AutoTokenizer.from_pretrained(\"google/flan-t5-large\")\n",
    "model = T5ForConditionalGeneration.from_pretrained(\"google/flan-t5-large\", device_map=\"auto\", torch_dtype=torch.float16)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Provide some initial text to prompt the model to generate the source and target prompts."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "source_concept = \"bowl\"\n",
    "target_concept = \"basket\"\n",
    "\n",
    "source_text = f\"Provide a caption for images containing a {source_concept}. \"\n",
    "\"The captions should be in English and should be no longer than 150 characters.\"\n",
    "\n",
    "target_text = f\"Provide a caption for images containing a {target_concept}. \"\n",
    "\"The captions should be in English and should be no longer than 150 characters.\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Next, create a utility function to generate the prompts:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "@torch.no_grad()\n",
    "def generate_prompts(input_prompt):\n",
    "    input_ids = tokenizer(input_prompt, return_tensors=\"pt\").input_ids.to(\"cuda\")\n",
    "\n",
    "    outputs = model.generate(\n",
    "        input_ids, temperature=0.8, num_return_sequences=16, do_sample=True, max_new_tokens=128, top_k=10\n",
    "    )\n",
    "    return tokenizer.batch_decode(outputs, skip_special_tokens=True)\n",
    "\n",
    "source_prompts = generate_prompts(source_text)\n",
    "target_prompts = generate_prompts(target_text)\n",
    "print(source_prompts)\n",
    "print(target_prompts)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "> [!TIP]\n",
    "> Check out the [generation strategy](https://huggingface.co/docs/transformers/main/en/generation_strategies) guide if you're interested in learning more about strategies for generating different quality text.\n",
    "\n",
    "Load the text encoder model used by the [StableDiffusionDiffEditPipeline](https://huggingface.co/docs/diffusers/main/en/api/pipelines/diffedit#diffusers.StableDiffusionDiffEditPipeline) to encode the text. You'll use the text encoder to compute the text embeddings:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "from diffusers import StableDiffusionDiffEditPipeline\n",
    "\n",
    "pipeline = StableDiffusionDiffEditPipeline.from_pretrained(\n",
    "    \"stabilityai/stable-diffusion-2-1\", torch_dtype=torch.float16, use_safetensors=True\n",
    ")\n",
    "pipeline.enable_model_cpu_offload()\n",
    "pipeline.enable_vae_slicing()\n",
    "\n",
    "@torch.no_grad()\n",
    "def embed_prompts(sentences, tokenizer, text_encoder, device=\"cuda\"):\n",
    "    embeddings = []\n",
    "    for sent in sentences:\n",
    "        text_inputs = tokenizer(\n",
    "            sent,\n",
    "            padding=\"max_length\",\n",
    "            max_length=tokenizer.model_max_length,\n",
    "            truncation=True,\n",
    "            return_tensors=\"pt\",\n",
    "        )\n",
    "        text_input_ids = text_inputs.input_ids\n",
    "        prompt_embeds = text_encoder(text_input_ids.to(device), attention_mask=None)[0]\n",
    "        embeddings.append(prompt_embeds)\n",
    "    return torch.concatenate(embeddings, dim=0).mean(dim=0).unsqueeze(0)\n",
    "\n",
    "source_embeds = embed_prompts(source_prompts, pipeline.tokenizer, pipeline.text_encoder)\n",
    "target_embeds = embed_prompts(target_prompts, pipeline.tokenizer, pipeline.text_encoder)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Finally, pass the embeddings to the [generate_mask()](https://huggingface.co/docs/diffusers/main/en/api/pipelines/diffedit#diffusers.StableDiffusionDiffEditPipeline.generate_mask) and [invert()](https://huggingface.co/docs/diffusers/main/en/api/pipelines/diffedit#diffusers.StableDiffusionDiffEditPipeline.invert) functions, and pipeline to generate the image:\n",
    "\n",
    "```diff\n",
    "  from diffusers import DDIMInverseScheduler, DDIMScheduler\n",
    "  from diffusers.utils import load_image, make_image_grid\n",
    "  from PIL import Image\n",
    "\n",
    "  pipeline.scheduler = DDIMScheduler.from_config(pipeline.scheduler.config)\n",
    "  pipeline.inverse_scheduler = DDIMInverseScheduler.from_config(pipeline.scheduler.config)\n",
    "\n",
    "  img_url = \"https://github.com/Xiang-cd/DiffEdit-stable-diffusion/raw/main/assets/origin.png\"\n",
    "  raw_image = load_image(img_url).resize((768, 768))\n",
    "\n",
    "  mask_image = pipeline.generate_mask(\n",
    "      image=raw_image,\n",
    "-     source_prompt=source_prompt,\n",
    "-     target_prompt=target_prompt,\n",
    "+     source_prompt_embeds=source_embeds,\n",
    "+     target_prompt_embeds=target_embeds,\n",
    "  )\n",
    "\n",
    "  inv_latents = pipeline.invert(\n",
    "-     prompt=source_prompt,\n",
    "+     prompt_embeds=source_embeds,\n",
    "      image=raw_image,\n",
    "  ).latents\n",
    "\n",
    "  output_image = pipeline(\n",
    "      mask_image=mask_image,\n",
    "      image_latents=inv_latents,\n",
    "-     prompt=target_prompt,\n",
    "-     negative_prompt=source_prompt,\n",
    "+     prompt_embeds=target_embeds,\n",
    "+     negative_prompt_embeds=source_embeds,\n",
    "  ).images[0]\n",
    "  mask_image = Image.fromarray((mask_image.squeeze()*255).astype(\"uint8\"), \"L\")\n",
    "  make_image_grid([raw_image, mask_image, output_image], rows=1, cols=3)\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Generate a caption for inversion"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "While you can use the `source_prompt` as a caption to help generate the partially inverted latents, you can also use the [BLIP](https://huggingface.co/docs/transformers/model_doc/blip) model to automatically generate a caption.\n",
    "\n",
    "Load the BLIP model and processor from the 🤗 Transformers library:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "from transformers import BlipForConditionalGeneration, BlipProcessor\n",
    "\n",
    "processor = BlipProcessor.from_pretrained(\"Salesforce/blip-image-captioning-base\")\n",
    "model = BlipForConditionalGeneration.from_pretrained(\"Salesforce/blip-image-captioning-base\", torch_dtype=torch.float16, low_cpu_mem_usage=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Create a utility function to generate a caption from the input image:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "@torch.no_grad()\n",
    "def generate_caption(images, caption_generator, caption_processor):\n",
    "    text = \"a photograph of\"\n",
    "\n",
    "    inputs = caption_processor(images, text, return_tensors=\"pt\").to(device=\"cuda\", dtype=caption_generator.dtype)\n",
    "    caption_generator.to(\"cuda\")\n",
    "    outputs = caption_generator.generate(**inputs, max_new_tokens=128)\n",
    "\n",
    "    # offload caption generator\n",
    "    caption_generator.to(\"cpu\")\n",
    "\n",
    "    caption = caption_processor.batch_decode(outputs, skip_special_tokens=True)[0]\n",
    "    return caption"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Load an input image and generate a caption for it using the `generate_caption` function:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from diffusers.utils import load_image\n",
    "\n",
    "img_url = \"https://github.com/Xiang-cd/DiffEdit-stable-diffusion/raw/main/assets/origin.png\"\n",
    "raw_image = load_image(img_url).resize((768, 768))\n",
    "caption = generate_caption(raw_image, model, processor)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<div class=\"flex justify-center\">\n",
    "    <figure>\n",
    "        <img class=\"rounded-xl\" src=\"https://github.com/Xiang-cd/DiffEdit-stable-diffusion/raw/main/assets/origin.png\"/>\n",
    "        <figcaption class=\"text-center\">generated caption: \"a photograph of a bowl of fruit on a table\"</figcaption>\n",
    "    </figure>\n",
    "</div>\n",
    "\n",
    "Now you can drop the caption into the [invert()](https://huggingface.co/docs/diffusers/main/en/api/pipelines/diffedit#diffusers.StableDiffusionDiffEditPipeline.invert) function to generate the partially inverted latents!"
   ]
  }
 ],
 "metadata": {},
 "nbformat": 4,
 "nbformat_minor": 4
}
